//
//  WBComposePictureView.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/24.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit

private let CollectionViewCellID = "UICollectionViewCell"
class WBComposePictureView: UICollectionView {
    
    // MARK: -  告知外界弹出图片选择控制器
    var ComposePictureViewClosure: (()->())?
    
    // MARK: -  图片数组属性
    var images: [UIImage] = [UIImage]()

    // MARK: -  重写init方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUpUI()
    }
    
    // MARK: -  供外界调用方法   往数组里面添加图片
    func addImage(image image: UIImage) {
        
        images.insert(image, atIndex: 0)
        
        if images.count > 9 {
            
            images.removeLast()
        }
        
        if images.count > 0 {
            
            self.hidden = false
        }
        
        reloadData()
    }
    
    // MARK: -  设置UI
    private func setUpUI() {
        
        self.backgroundColor = UIColor.whiteColor()
        
        self.hidden = true
        dataSource = self
        delegate = self
        
        registerClass(WBComposePictureViewCell.self, forCellWithReuseIdentifier: CollectionViewCellID)
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        let margin: CGFloat = 5
        let cellWH = (kScreenW - 20 - margin * 2) / 3
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
    }
    
    // MARK: -  重写init方法时必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


// MARK: -  数据源和代理方法
extension WBComposePictureView: UICollectionViewDelegate, UICollectionViewDataSource {
    
    
    
    // MARK: -  cell被点击时候调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count {
            
            ComposePictureViewClosure?()
        }
    }
    
    // MARK: -  设置item
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = self.dequeueReusableCellWithReuseIdentifier(CollectionViewCellID, forIndexPath: indexPath) as! WBComposePictureViewCell
        if indexPath.item == images.count {
            
            cell.image = nil
            
        }else {
            
            cell.image = images[indexPath.item]
        }
        
        cell.composePictureViewCellClosure = { [weak self] in
            
            self?.images.removeAtIndex(indexPath.item)
            if self?.images.count <= 0 {
                
                self?.hidden = true
            }
            
            self?.reloadData()
        }
        return cell
    }
    
    // MARK: -  item的个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images.count
        if count == 9 || count == 0 {
            return count
        }else {
            return count + 1
        }
//        return images.count
    }
}

// MARK: -  自定义cell
class WBComposePictureViewCell: UICollectionViewCell {
    
    // MARK: -  点击删除按钮时调用的闭包
    var composePictureViewCellClosure: (()->())?
    
    // MARK: -  image属性
    var image: UIImage? {
        
        didSet {
            
            if image != nil {
                
                backgroundImageView.image = image
                backgroundImageView.highlightedImage = nil
                deleteButton.hidden = false
                
            }else {
                
                backgroundImageView.image = UIImage(named: "compose_pic_add")
                backgroundImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            }
        }
    }
    
    // MARK: -  重写init方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setUpUI()
    }
    
    // MARK: -  设置视图
    private func setUpUI() {
        
        contentView.addSubview(backgroundImageView)
        contentView.addSubview(deleteButton)
        
        backgroundImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
    }
    
    // MARK: -  重写init方法时必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  懒加载删除按钮
    private lazy var deleteButton: UIButton = {
        
        let deleteButton = UIButton()
        deleteButton.addTarget(self, action: "clickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
        deleteButton.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return deleteButton
        }()
    
    // MARK: -  删除按钮的点击事件
    @objc private func clickDeleteButton() {
        
        composePictureViewCellClosure?()
        
    }

    // MARK: -  懒加载背景imageView
    private lazy var backgroundImageView: UIImageView = UIImageView()
}
